import sys
import pygame
from bullet import Bullet
from alien import Alien
from time import sleep

def check_keydown_events(event, ai_settings, screen, ship, bullets):
    if event.key == pygame.K_RIGHT:
        # Move the ship to the right.
        ship.moving_right = True
        
    if event.key == pygame.K_LEFT:   
        # Move the ship to the left.
        ship.moving_left = True
        
    if event.key == pygame.K_UP:
        # Move the ship up.
        ship.moving_up = True
        
    if event.key == pygame.K_DOWN:
        # Move the ship down.
        ship.moving_down = True     
          
    elif event.key == pygame.K_SPACE:
        fire_bullets(ai_settings, screen, ship, bullets)
        
    elif event.key == pygame.K_q:
        sys.exit()

        
def check_keyup_events(event, ship):
    if event.key == pygame.K_RIGHT:
        # Stop Move the ship to the right.
        ship.moving_right = False
        
    if event.key == pygame.K_LEFT:   
        # Stop Move the ship to the left.
        ship.moving_left = False
        
    if event.key == pygame.K_UP:
        # Stop Move the ship up.
        ship.moving_up = False
        
    if event.key == pygame.K_DOWN:
        # Stop Move the ship down.
        ship.moving_down = False    

def check_events(ai_settings, screen, ship, aliens, 
                bullets, stats, play_button,
                score_board):
    """Respond to keypresses and mouse events. """
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
            
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event, ai_settings, \
                                screen, ship, bullets)
                             
        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)
        
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pygame.mouse.get_pos()
            check_play_button(ai_settings, screen, ship, aliens, bullets,
                            stats, play_button, mouse_x, mouse_y,
                            score_board)

def check_play_button(ai_settings, screen, ship, aliens, bullets, 
                    stats, play_button, mouse_x, mouse_y,
                    score_board):
    """ Start a new game when the player clicks Play. """
    button_clicked = play_button.rect.collidepoint(mouse_x,mouse_y)
    if button_clicked and not stats.game_active:
        ai_settings.initialize_dynamic_settings()
        stats.reset_stats()
        stats.game_active = True
        # Hide the mouse cursor
        pygame.mouse.set_visible(False)
        
        # Reset the score image
        score_board.prep_high_score()
        score_board.prep_level()
        score_board.prep_score()
        score_board.prep_ships()
        
        # Empty the list of aliens and bullets.
        aliens.empty()
        bullets.empty()
        
        # Create a new fleet
        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()

def check_high_score(stats, score_board):
    """ Check to see if there's a new high score. """
    if stats.score > stats.high_score:
        stats.high_score = stats.score
        score_board.prep_high_score()

def update_screen(ai_settings, screen, ship, base, 
                    aliens, bullets, stats, play_button, score_board):
    """Update images on the screen and flip to the new screen. """
    # Redraw the screen during each pass through the loop.
    screen.fill(ai_settings.bg_color)
    # Redraw all bullets behind ship and aliens
    for bullet in bullets.sprites():
        bullet.draw_bullet()
    
    # Display a ship according to its rect.
    base.blitme()
    ship.blitme()
    
    # Display the alien
    aliens.draw(screen)
    
    # Draw the score_board
    score_board.show_score()
    
    # Draw the play button if the game is inactive.
    if not stats.game_active:
        play_button.draw_button()
        
    # Make the most recently drawn screen visable.
    pygame.display.flip()
    
def update_bullets(ai_settings, aliens, bullets, stats, score_board):
    """ Update position of bullets and get rid of old bullets. """
    # Update the bullets group. Once call, all the element will call
    bullets.update()
    
    # Get rid of bullets that have disappear
    for bullet in bullets.copy():
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)
    
    check_bullets_collisions(ai_settings, aliens, 
                            bullets, stats, score_board)

def check_bullets_collisions(ai_settings, aliens, 
                            bullets, stats, score_board):    
    """    
    # Check for any bullets that have hit aliens.
    # If so, get rid of the bullet and the aliens. 
    # Return a dictionarys whose key is collided 
    # bullet and value is alien.
    """
    collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
    if collisions:
        for aliens in collisions.values():
            # Prevent only one score increment when kill multiple alien 
            # at the same time.
            stats.score += ai_settings.alien_scores
            score_board.prep_score()
        check_high_score(stats,score_board)
    

def update_aliens(ai_settings, screen, ship, aliens, bullets, stats, 
                score_board):
    """ Update the positions of all aliens in the fleet. """
    
    """ To check the fleet at the edge first in order to change moving 
     direction. """
    check_fleet_edges(ai_settings, aliens) 
    check_fleet_bottom(ai_settings, stats, screen,
                        ship, aliens, bullets, score_board)
    aliens.update()
    
    if len(aliens) == 0:
        ai_settings.increase_speed()
        create_fleet(ai_settings, screen, ship, aliens)
        stats.level += 1
        score_board.prep_level()
        
    # Check for alien-ship collisions. Ship is a sprite.
    if pygame.sprite.spritecollideany(ship,aliens):
        ship_hit(ai_settings, stats, screen, ship,
                aliens, bullets, score_board)

def fire_bullets(ai_settings, screen, ship, bullets):
    """ fire the bullets if limits not reached yet. """
    # Create a new bullet and add it to the bullets group.
    if len(bullets) < ai_settings.bullets_allowed:
        new_bullet = Bullet(ai_settings, screen, ship)
        bullets.add(new_bullet)     

def get_number_aliens_x(ai_settings, alien_width):
    """ Determine the number of aliens that fit in a row. """
    available_space_x = ai_settings.screen_width - 2*alien_width
    number_aliens_x = int(available_space_x/(2*alien_width))
    return number_aliens_x

def create_alien(ai_settings, screen, aliens, alien_number, row_number):
    # Create an alien and place it in the row.
    alien = Alien(ai_settings, screen)
    alien_width = alien.rect.width
    alien.x = alien_width + 2*alien_width*alien_number
    # Set the location of the new aliens. 
    alien.rect.x = alien.x
    alien.rect.y = alien.rect.height + 2*alien.rect.height*row_number
    aliens.add(alien)

def get_number_rows(ai_settings, ship_height, alien_height):
    """ 
    Determine the number of rows of aliens that fit on the screen.
    """
    available_space_y  = (ai_settings.screen_height \
                        - (4*alien_height) - ship_height)
    number_rows = int(available_space_y/(2*alien_height))
    return number_rows

       
def create_fleet(ai_settings, screen, ship, aliens):
    """ Create a full fleet of aliens. """
    # Create an alien and find the number of aliens in a row.
    # Spacing between each alien is equal to one alien width
    alien = Alien(ai_settings, screen)
    number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width)
    number_rows = get_number_rows(ai_settings, ship.rect.height, 
                                alien.rect.height)
                                
    # Create the first row of aliens.
    for row_number in range(number_rows):
        for alien_number in range(number_aliens_x):
            create_alien(ai_settings, screen, aliens, alien_number,
                        row_number)

def check_fleet_bottom(ai_settings, stats, screen,
                        ship, aliens, bullets, score_board):
    """ To check whether the aliens have reach the bottom. """
    screen_rect = screen.get_rect()
    for alien in aliens.sprites():
        if alien.rect.bottom >= screen_rect.bottom:
            # Treat this the same as if a ship got hit
            ship_hit(ai_settings, stats, screen,
                    ship, aliens, bullets, score_board)
            break
    

def check_fleet_edges(ai_settings, aliens):
    """ Respond appropriately if any aliens have reached an edge. """
    for alien in aliens.sprites():
        if alien.check_edges():
            change_fleet_direction(ai_settings,aliens)
            break

def change_fleet_direction(ai_settings, aliens):
    """ Drop the entire fleet and change the fleet's direction. """
    for alien in aliens.sprites():
        alien.rect.y += ai_settings.fleet_drop_speed
    ai_settings.fleet_direction *= -1

def ship_hit(ai_settings, stats, screen,
            ship, aliens, bullets, score_board):
    """ Respond to ship being hit by alien. """
    if stats.ships_left > 0:
        # Decrement ships_left.
        stats.ships_left -= 1
        
        # Empty the list of aliens and bullets.
        aliens.empty()
        bullets.empty()
        
        # Create a new fleet and center the ship. 
        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()
        
        # Pause.
        sleep(0.5)
        
        # Update the ship number in the left-top.
        score_board.prep_ships()
    else:
        stats.game_active = False
        # Display the mouse cursor again. 
        pygame.mouse.set_visible(True)
        
    
